﻿CREATE FUNCTION [dbo].[fn_QuoteName]
(
	@Name sysname
)
RETURNS sysname
AS
BEGIN
	
	SET @Name = REPLACE(REPLACE(@Name, '[', ''), ']', '')
	
	DECLARE @Object   AS sysname; SET @Object   = ISNULL(QUOTENAME(PARSENAME(@Name, 1)), '')
	DECLARE @Owner    AS sysname; SET @Owner    = ISNULL(QUOTENAME(PARSENAME(@Name, 2)) + '.', '')
	DECLARE @Database AS sysname; SET @Database = ISNULL(QUOTENAME(PARSENAME(@Name, 3)) + '.', '')
	DECLARE @Server   AS sysname; SET @Server   = ISNULL(QUOTENAME(PARSENAME(@Name, 4)) + '.', '')
	
	SET @Name = @Server + @Database + @Owner + @Object

	RETURN @Name
END